import BTComposite from "../../Base/BTComposite";
import { NodeStatus } from "../../Enum";

export default class CompositeRandomSelector extends BTComposite
{
    executionOrder: Array<number> = [];

    get index()
    {
        return this.executionOrder[this.executionOrder.length - 1];
    }

    onStart()
    {
        super.onStart();
        this.shuffle();
    }

    shuffle()
    {
        this.executionOrder = [];
        const indexlist = Array.from({ length: this.childens.length }, (e, i: number) => i);
        for (let j = indexlist.length - 1; j >= 0; j--)
        {
            const randomIndex = Math.floor(Math.random() * indexlist.length);
            this.executionOrder.push(indexlist.splice(randomIndex, 1)[0]);
        }
    }

    canExecute()
    {
        return this.executionOrder.length && this.status !== NodeStatus.Success;
    }

    onChildExecuted(childStatus)
    {
        switch (childStatus)
        {
            case NodeStatus.Success:
                this.status = NodeStatus.Success;
                break;
            case NodeStatus.Failure:
                this.executionOrder.pop();
                if (!this.executionOrder.length)
                {
                    this.status = NodeStatus.Failure;
                } else
                {
                    this.status = NodeStatus.Running;
                }
                break;
            case NodeStatus.Running:
                this.status = NodeStatus.Running;
                break;
            default:
                break;
        }
    }

    onConditionalAbort(index: number)
    {
        this.shuffle();
        this.status = NodeStatus.Inactive;
    }

/*    onUpdate()
    {
        if (this.status === NodeStatus.Success)
        {
            return this.status;
        }
        if (!this.executionOrder.length)
        {
            this.status = NodeStatus.Success;
            return this.status;
        }

        const child = this.childens[this.index];
        const res = child.run();
        if (res === NodeStatus.Success)
        {
            this.status = NodeStatus.Success;
            return this.status;
        }
        if (res === NodeStatus.Failure)
        {
            this.executionOrder.pop();
        }
        return NodeStatus.Running;
    }*/
}